//
//  HomePageViewController.m
//  Telemedicine
//
//  Created by Trong Ton on 5/14/14.
//  Copyright (c) 2014 Trong Ton. All rights reserved.
//

#import "HomePageViewController.h"
#import "AppDelegate.h"
#import "JSON.h"
#import "JMImageCache.h"

@interface HomePageViewController ()

@end

@implementation HomePageViewController

- (void)registerKeyboardNotification {
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWasShown:)
                                                 name:UIKeyboardDidShowNotification
                                               object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillBeHidden:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];
}

- (void)unregisterKeyboardNotification {
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:UIKeyboardDidShowNotification
                                                  object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:UIKeyboardDidHideNotification
                                                  object:nil];
}

- (void)keyboardWasShown:(NSNotification*)aNotification {
    isShowKeyBoard = YES;
    NSDictionary* info = [aNotification userInfo];
#if __IPHONE_OS_VERSION_MIN_REQUIRED > __IPHONE_3_1
    CGSize kbSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
#else
    CGSize kbSize = [[info objectForKey:UIKeyboardBoundsUserInfoKey] CGRectValue].size;
#endif
    if(UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone)
    {
        CGSize result = [[UIScreen mainScreen] bounds].size;
        if(result.height == 568)
        {
            self.view.frame = CGRectMake(self.view.frame.origin.x, 0 - 60, self.view.frame.size.width, self.view.frame.size.height);
        }
        else {
            self.view.frame = CGRectMake(self.view.frame.origin.x, 0 - 100, self.view.frame.size.width, self.view.frame.size.height);
        }
    }
    UITapGestureRecognizer *taprecog = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideKeyboard)];
    taprecog.numberOfTapsRequired = 1;
    taprecog.numberOfTouchesRequired = 1;
    [[AppDelegate sharedDelegate].window addGestureRecognizer:taprecog];
    [taprecog release];
}

// Called when the UIKeyboardWillHideNotification is sent
- (void)keyboardWillBeHidden:(NSNotification*)aNotification {
    isShowKeyBoard = NO;
    for(UIGestureRecognizer *gesture in [[AppDelegate sharedDelegate].window gestureRecognizers]) {
        gesture.enabled = NO;
    }
    self.view.frame = CGRectMake(self.view.frame.origin.x, 0, self.view.frame.size.width, self.view.frame.size.height);
}


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
//    self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"home_bottom.jpg"]];
    
    NSArray *vComp = [[UIDevice currentDevice].systemVersion componentsSeparatedByString:@"."];
    int startYView = ([[vComp objectAtIndex:0] intValue] >= 7)?20:0;
    
    UIScrollView *contentView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, startYView, 320, self.view.bounds.size.height - 49 - startYView)];
//    contentView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"home_bottom.jpg"]];
    [self.view addSubview:contentView];
    [contentView release];
        
    UIImageView *bigImage = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, contentView.bounds.size.width, 218)];
    NSString *linkImage = [[NSUserDefaults standardUserDefaults] objectForKey:@"BackgroundImageLink"];
    if (linkImage && linkImage.length > 0) {
        [bigImage setImageWithURL:[NSURL URLWithString:linkImage] placeholder:[UIImage imageNamed:@"background_call_default.jpg"]];
    }
    else {
        bigImage.image = [UIImage imageNamed:@"background_call_default.jpg"];
    }
//    [bigImage setImage:[UIImage imageNamed:@"background_call_default.jpg"]];
    [contentView addSubview:bigImage];
    [bigImage release];
    
    UIButton *registryCall = [UIButton buttonWithType:UIButtonTypeCustom];
    registryCall.frame = CGRectMake(0, bigImage.bounds.size.height, contentView.bounds.size.width, 62);
    registryCall.backgroundColor = [UIColor whiteColor];
    [registryCall setBackgroundImage:[UIImage imageNamed:@"touch_here.png"] forState:UIControlStateNormal];
    [registryCall setBackgroundImage:[UIImage imageNamed:@"touch_here_hover.png"] forState:UIControlStateHighlighted];
    [registryCall addTarget:self action:@selector(registryCallPress:) forControlEvents:UIControlEventTouchUpInside];
    [contentView addSubview:registryCall];
    
    int startY = registryCall.frame.origin.y + registryCall.frame.size.height;
    UIView *spaceEmpty = [[UIView alloc] initWithFrame:CGRectMake(0, startY, contentView.frame.size.width, 5)];
    spaceEmpty.backgroundColor = [UIColor whiteColor];
    [contentView addSubview:spaceEmpty];
    [spaceEmpty release];
    
    startY += 5;
    UIImageView *advertiseBanner1 = [[UIImageView alloc] initWithFrame:CGRectMake(0, startY, contentView.bounds.size.width, 48)];
    [advertiseBanner1 setImage:[UIImage imageNamed:@"home_minduration_banner.jpg"]];
    [contentView addSubview:advertiseBanner1];
    [advertiseBanner1 release];
    
    startY += 48;
    UIImageView *advertiseBanner2 = [[UIImageView alloc] initWithFrame:CGRectMake(0, startY, contentView.bounds.size.width, 48)];
    [advertiseBanner2 setImage:[UIImage imageNamed:@"home_patient_banner.jpg"]];
    [contentView addSubview:advertiseBanner2];
    [advertiseBanner2 release];
    
    startY += 48;
    UIImageView *advertiseBanner3 = [[UIImageView alloc] initWithFrame:CGRectMake(0, startY, contentView.bounds.size.width, 48)];
    [advertiseBanner3 setImage:[UIImage imageNamed:@"home_patient_issue_banner.jpg"]];
    [contentView addSubview:advertiseBanner3];
    [advertiseBanner3 release];
    
    startY += 48;
    if(startY < contentView.bounds.size.height - 23) {
        startY = contentView.bounds.size.height - 23;
    }
    UIImageView *phoneInfo = [[UIImageView alloc] initWithFrame:CGRectMake(0, startY, contentView.bounds.size.width, 23)];
    [phoneInfo setImage:[UIImage imageNamed:@"home_bottomwebsite_url.jpg"]];
    [contentView addSubview:phoneInfo];
    [phoneInfo release];
    
    [contentView setContentSize:CGSizeMake(contentView.bounds.size.width, (startY + 23))];//startY+bottomView.bounds.size.height)];
    contentView.scrollEnabled = YES;
    
    [self registerKeyboardNotification];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc {
//    if (closeForm) {
//        [closeForm release];
//    }
    [self unregisterKeyboardNotification];
    [super dealloc];
}

- (void) registryCallPress:(id)sender {
    [self registryForm];
}

- (void)registryForm {
    if (closeForm == nil) {
        closeForm = [UIButton buttonWithType:UIButtonTypeCustom];
        closeForm.frame = self.view.bounds;
        closeForm.backgroundColor = [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:0.6];
        [closeForm addTarget:self action:@selector(closeFormPress:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:closeForm];
        [closeForm retain];
        
        UIView *backgroundForm = [[UIView alloc] initWithFrame:CGRectMake(20, (self.view.bounds.size.height - 300)/2, 280, 300)];
        backgroundForm.backgroundColor = [UIColor whiteColor];
        [closeForm addSubview:backgroundForm];
        [backgroundForm release];
        
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 280, 200)];
        imageView.image = [UIImage imageNamed:@"bg_dialog_code.jpg"];
        [backgroundForm addSubview:imageView];
        [imageView release];
        
        UIImageView *avatartImage = [[UIImageView alloc] initWithFrame:CGRectMake(0, 80, 280, 40)];
        avatartImage.image = [UIImage imageNamed:@"bg_start_to_make_call_button.png"];
        [imageView addSubview:avatartImage];
        [avatartImage release];
        
        phoneImage = [UIButton buttonWithType:UIButtonTypeCustom];
        phoneImage.frame = CGRectMake(10, 148, 32, 32);
        [phoneImage setBackgroundImage:[UIImage imageNamed:@"back-button.png"] forState:UIControlStateNormal];
        [phoneImage setBackgroundImage:[UIImage imageNamed:@"ic_telephone_handset.png"] forState:UIControlStateDisabled];
        phoneImage.enabled = NO;
        [phoneImage addTarget:self action:@selector(backRegistryPress:) forControlEvents:UIControlEventTouchUpInside];
        [backgroundForm addSubview:phoneImage];
        
        UIView *spaceLine = [[UIView alloc] initWithFrame:CGRectMake(0, 198, 280, 2)];
        spaceLine.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"home_bottom.jpg"]];
        [imageView addSubview:spaceLine];
        [spaceLine release];
        
        UIView *leftSpaceLine = [[UIView alloc] initWithFrame:CGRectMake(0, 190, 59, 8)];
        leftSpaceLine.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"home_bottom.jpg"]];
        [imageView addSubview:leftSpaceLine];
        [leftSpaceLine release];
        
        functionBox = [[UIView alloc] initWithFrame:CGRectMake(0, 200, 280, 100)];
        [backgroundForm addSubview:functionBox];
        [functionBox release];
        
        UIButton *getCodeButton = [UIButton buttonWithType:UIButtonTypeCustom];
        getCodeButton.frame = CGRectMake(20, 5, 240, 25);
        [getCodeButton setBackgroundImage:[UIImage imageNamed:@"btn_genrate_code.jpg"] forState:UIControlStateNormal];
        [getCodeButton addTarget:self action:@selector(getCodePress:) forControlEvents:UIControlEventTouchUpInside];
        [functionBox addSubview:getCodeButton];
        
        UIImageView *checkCode = [[UIImageView alloc] initWithFrame:CGRectMake(20, 35, 240, 25)];
        checkCode.image = [UIImage imageNamed:@"btn_check_code.jpg"];
        [functionBox addSubview:checkCode];
        [checkCode release];
        
        UIView *lineCodeTextField = [[UIView alloc]initWithFrame:CGRectMake(25, 90, 195, 1)];
        lineCodeTextField.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"home_bottom.jpg"]];
        [functionBox addSubview:lineCodeTextField];
        [lineCodeTextField release];
        
        codeTextField = [[UITextField alloc] initWithFrame:CGRectMake(30, 70, 185, 18)];
        codeTextField.placeholder = @"Submit your code here";
        codeTextField.textColor = [UIColor blackColor];
        codeTextField.returnKeyType = UIReturnKeyDefault;
        codeTextField.font = [UIFont systemFontOfSize:14];
        codeTextField.delegate = self;
        [functionBox addSubview:codeTextField];
        [codeTextField release];
        
        submitCode= [UIButton buttonWithType:UIButtonTypeCustom];
        submitCode.frame = CGRectMake(225, 64, 32, 32);
        [submitCode setBackgroundImage:[UIImage imageNamed:@"send_code_button.png"] forState:UIControlStateNormal];
        [submitCode addTarget:self action:@selector(submitCodePress:) forControlEvents:UIControlEventTouchUpInside];
        [functionBox addSubview:submitCode];
        
//        UILabel *getCodeLable = [[UILabel alloc] initWithFrame:CGRectMake(10, 60, 205, 18)];
//        getCodeLable.font = [UIFont systemFontOfSize:12];
//        getCodeLable.text = @"Don't have code? Click here to get it";
//        [functionBox addSubview:getCodeLable];
//        [getCodeLable release];
//        
////        UIView *spaceLineGetCode = [[UIView alloc] initWithFrame:CGRectMake(225, 58, 1, 18)];
////        spaceLineGetCode.backgroundColor = [UIColor colorWithRed:238.0/255.0 green:238.0/255.0 blue:238.0/255.0 alpha:1.0];
////        [functionBox addSubview:spaceLineGetCode];
////        [spaceLineGetCode release];
//        
//        UIButton *getCodeButton = [UIButton buttonWithType:UIButtonTypeCustom];
//        getCodeButton.frame = CGRectMake(215, 49, 40, 40);
//        [getCodeButton setBackgroundImage:[UIImage imageNamed:@"get_a_code_button.png"] forState:UIControlStateNormal];
//        [getCodeButton addTarget:self action:@selector(getCodePress:) forControlEvents:UIControlEventTouchUpInside];
//        [functionBox addSubview:getCodeButton];
//        
//        UIView *bottonLineGetCode = [[UIView alloc] initWithFrame:CGRectMake(5, 80, 230, 1)];
//        bottonLineGetCode.backgroundColor = [UIColor colorWithRed:238.0/255.0 green:238.0/255.0 blue:238.0/255.0 alpha:1.0];
//        [functionBox addSubview:bottonLineGetCode];
//        [bottonLineGetCode release];
        
        UIView *bottomLine = [[UIView alloc] initWithFrame:CGRectMake(0, 98, 280, 2)];
        bottomLine.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"home_bottom.jpg"]];
        [functionBox addSubview:bottomLine];
        [bottomLine release];
    }
    else {
        if (contentGetCode) {
            [contentGetCode removeFromSuperview];
        }
        phoneImage.enabled = NO;
    }
    CATransition *transition = [CATransition animation];
    transition.duration = 1.0f;
    transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    transition.type = kCATransitionFade;
    transition.subtype = kCATransitionPush;
    transition.delegate = self;
    [self.view.layer addAnimation:transition forKey:nil];
    [self.view addSubview:closeForm];
    [closeForm release];
}

- (void)showFormGetCode {
    if (contentGetCode == nil) {
        contentGetCode = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 280, 100)];
        contentGetCode.backgroundColor = [UIColor whiteColor];
        
        skypeTextField = [[UITextField alloc] initWithFrame:CGRectMake(10, 15, 210, 23)];
        skypeTextField.placeholder = @"Skype Name";
        skypeTextField.textColor = [UIColor blackColor];
        skypeTextField.autocorrectionType = NO;
        skypeTextField.autocapitalizationType = UITextAutocapitalizationTypeNone;
        skypeTextField.returnKeyType = UIReturnKeyNext;
        skypeTextField.font = [UIFont systemFontOfSize:14];
        skypeTextField.delegate = self;
        [contentGetCode addSubview:skypeTextField];
        [skypeTextField release];
        
        UIView *lineSkypeTextField = [[UIView alloc]initWithFrame:CGRectMake(5, 39, 220, 1)];
        lineSkypeTextField.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"home_bottom.jpg"]];
        [contentGetCode addSubview:lineSkypeTextField];
        [lineSkypeTextField release];
        
        emailTextField = [[UITextField alloc] initWithFrame:CGRectMake(10, 50, 210, 23)];
        emailTextField.placeholder = @"Email";
        emailTextField.textColor = [UIColor blackColor];
        emailTextField.returnKeyType = UIReturnKeyDefault;
        emailTextField.keyboardType = UIKeyboardTypeEmailAddress;
        emailTextField.font = [UIFont systemFontOfSize:14];
        emailTextField.autocorrectionType = NO;
        emailTextField.autocapitalizationType = UITextAutocapitalizationTypeNone;
        emailTextField.delegate = self;
        [contentGetCode addSubview:emailTextField];
        [emailTextField release];
        
        UIView *lineEmailTextField = [[UIView alloc]initWithFrame:CGRectMake(5, 74, 220, 1)];
        lineEmailTextField.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"home_bottom.jpg"]];
        [contentGetCode addSubview:lineEmailTextField];
        [lineEmailTextField release];
        
        submitCode= [UIButton buttonWithType:UIButtonTypeCustom];
        submitCode.frame = CGRectMake(240, 34, 32, 32);
        [submitCode setBackgroundImage:[UIImage imageNamed:@"send_code_button.png"] forState:UIControlStateNormal];
        [submitCode addTarget:self action:@selector(sendButtonPress:) forControlEvents:UIControlEventTouchUpInside];
        [contentGetCode addSubview:submitCode];
        
//        UIButton *sendButton = [UIButton buttonWithType:UIButtonTypeCustom];
//        sendButton.frame = CGRectMake(20, 65, 80, 20);
//        sendButton.backgroundColor = [UIColor colorWithRed:73.0/255.0 green:121.0/255.0 blue:141.0/255.0 alpha:1.0];
////        sendButton.layer.cornerRadius = 4;
//        [sendButton setTitle:@"Get Code" forState:UIControlStateNormal];
//        sendButton.titleLabel.font = [UIFont systemFontOfSize:12];
//        [sendButton addTarget:self action:@selector(sendButtonPress:) forControlEvents:UIControlEventTouchUpInside];
//        [contentGetCode addSubview:sendButton];
//        
//        UIButton *cancelButton = [UIButton buttonWithType:UIButtonTypeCustom];
//        cancelButton.frame = CGRectMake(110, 65, 80, 20);
//        cancelButton.backgroundColor = [UIColor colorWithRed:73.0/255.0 green:121.0/255.0 blue:141.0/255.0 alpha:1.0];
////        cancelButton.layer.cornerRadius = 4;
//        cancelButton.titleLabel.font = [UIFont systemFontOfSize:12];
//        [cancelButton setTitle:@"Cancel" forState:UIControlStateNormal];
//        [cancelButton addTarget:self action:@selector(cancelButtonPress:) forControlEvents:UIControlEventTouchUpInside];
//        [contentGetCode addSubview:cancelButton];
        
        UIView *bottomLine = [[UIView alloc] initWithFrame:CGRectMake(0, 98, 280, 2)];
        bottomLine.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"home_bottom.jpg"]];
        [contentGetCode addSubview:bottomLine];
        [bottomLine release];
    }
    else {
        skypeTextField.text = @"";
        emailTextField.text = @"";
    }
    phoneImage.enabled = YES;
    
    CATransition *transition = [CATransition animation];
    transition.duration = 1.0f;
    transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    transition.type = kCATransitionMoveIn;
    transition.subtype = kCATransitionFromRight;
    transition.delegate = self;
    [functionBox.layer addAnimation:transition forKey:nil];
    [functionBox addSubview:contentGetCode];
    
    [skypeTextField becomeFirstResponder];
}

- (void)closeFormPress:(id)sender {
//    [closeForm retain];
    
    CATransition *transition = [CATransition animation];
    transition.duration = 1.0f;
    transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    transition.type = kCATransitionFade;
    transition.subtype = kCATransitionReveal;
    transition.delegate = self;
    [self.view.layer addAnimation:transition forKey:nil];
    [closeForm removeFromSuperview];
    closeForm = nil;
}

- (void)submitCodePress:(id)sender {
    NSString *codeString = codeTextField.text;
    if (codeString && codeString.length > 3 &&  codeString.length < 7) {
        [self hideKeyboard];
        [self sentCodeToServer:codeString];
    }
    else {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Alert !" message:@"A vaild codes is from 4-6 characters. Please try agian" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alertView show];
        [alertView release];
    }
}

- (void)getCodePress:(id)sender {
    [self showFormGetCode];
}

- (void)backRegistryPress:(id)sender {
    if (contentGetCode) {
        CATransition *transition = [CATransition animation];
        transition.duration = 1.0f;
        transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
        transition.type = kCATransitionReveal;
        transition.subtype = kCATransitionFromLeft;
        transition.delegate = self;
        [functionBox.layer addAnimation:transition forKey:nil];
        [contentGetCode removeFromSuperview];
    }
    phoneImage.enabled = NO;
}

- (void)sendButtonPress:(id)sender {
    NSString *skypeString = skypeTextField.text!=nil?skypeTextField.text:@"";
    NSString *emailString = emailTextField.text!=nil?emailTextField.text:@"";
    if(skypeString.length > 0 && emailString.length > 0) {
        BOOL emailValidate = [self NSStringIsValidEmail:emailString];
        if (emailValidate) {
            [self hideKeyboard];
            [self getCodeFromServer:skypeString withEmail:emailString];
        }
        else {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Alert !" message:@"Your Email Address is in invalid format, please input a correct one." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
            [alert show];
            [alert release];
        }
    }
    else {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Alert !" message:@"Skype or email was empty. Please input it to signup." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alert show];
        [alert release];
    }
}

- (void)hideKeyboard {
    [activeField resignFirstResponder];
    activeField = nil;
}

-(BOOL) NSStringIsValidEmail:(NSString *)checkString
{
    BOOL stricterFilter = YES; // Discussion http://blog.logichigh.com/2010/09/02/validating-an-e-mail-address/
    NSString *stricterFilterString = @"[A-Z0-9a-z\\._%+-]+@([A-Za-z0-9-]+\\.)+[A-Za-z]{2,4}";
    NSString *laxString = @".+@([A-Za-z0-9]+\\.)+[A-Za-z]{2}[A-Za-z]*";
    NSString *emailRegex = stricterFilter ? stricterFilterString : laxString;
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:checkString];
}

#pragma mark - API methods

- (void)sentCodeToServer:(NSString *)codeString {
    //https://wp-dot-erudite-stratum-347.appspot.com/ws-user-new?code=adfdf
    if([AppDelegate sharedDelegate].isNetworkAvailable) {
        submitCode.enabled = NO;
        APIsBaseService *serVice = [APIsBaseService service];
        NSMutableDictionary *param = [NSMutableDictionary dictionary];
        [param setObject:codeString forKey:@"code"];
        
        [serVice requestWithURL:kCheckCodeValidate
                         params:param
                   successBlock:^(NSDictionary *dictionary){
                       NSLog(@"dic = %@", [dictionary description]);
                       NSString *codeString = [dictionary objectForKey:@"code"];
                       if(codeString && codeString.length > 0) {
                           NSString *skype = [dictionary objectForKey:@"skype_name"];
                           [[NSUserDefaults standardUserDefaults] setObject:skype forKey:@"your_skype"];
                           [[NSUserDefaults standardUserDefaults] setObject:codeString forKey:@"code"];
                           [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"wasLogin"];
                           [[NSUserDefaults standardUserDefaults] synchronize];
                           dispatch_async(dispatch_get_main_queue(), ^{
                               [[AppDelegate sharedDelegate] updateNotifyWhenChangeStatusLogin];
                               [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"showOpendSkype"];
                               [[AppDelegate sharedDelegate] addCallDoctorView];
                           });
                       }
                       else {
                           codeTextField.text = @"";
                           UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Alert !" message:@"Your code does not exit. Please generate new code!" delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
                           [alert show];
                           [alert release];
                       }
                       submitCode.enabled = YES;
                   }
                     errorBlock:^(NSError *error){
                         submitCode.enabled = YES;
                         NSDictionary *userInfo = [error userInfo];
                         NSString *errorString = [userInfo objectForKey:@"NSLocalizedDescription"];
                         UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Alert !" message:errorString delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
                         [alert show];
                         [alert release];
                     }
                     httpMethod:@"GET"];
    }
    else {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Alert" message:@"No internet connections, please check your settings." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alertView show];
        [alertView release];
    }
}

- (void)getCodeFromServer:(NSString *)skype withEmail:(NSString *)email {
    //https://wp-dot-erudite-stratum-347.appspot.com/code_controller/check
    if([AppDelegate sharedDelegate].isNetworkAvailable) {
        APIsBaseService *serVice = [APIsBaseService service];
        NSMutableDictionary *param = [NSMutableDictionary dictionary];
        [param setObject:skype forKey:@"skype_name"];
        [param setObject:email forKey:@"email_address"];
        
        [serVice requestWithURL:kGetCodeSignIn
                         params:param
                   successBlock:^(NSDictionary *dictionary){
                       NSLog(@"dic = %@", [dictionary description]);
                       NSString *codeString = [dictionary objectForKey:@"code"];
                       if(codeString && codeString.length > 0) {
                           [[NSUserDefaults standardUserDefaults] setObject:skype forKey:@"your_skype"];
                           [[NSUserDefaults standardUserDefaults] setObject:codeString forKey:@"code"];
                           [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"wasLogin"];
                           [[NSUserDefaults standardUserDefaults] synchronize];
                           
                           dispatch_async(dispatch_get_main_queue(), ^{
                               [[AppDelegate sharedDelegate] updateNotifyWhenChangeStatusLogin];
                               [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"showOpendSkype"];
                               [[AppDelegate sharedDelegate] addCallDoctorView];
                               
                           });
                           
                       }
                       else {
                           UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Alert !" message:@"An unknow error has occurred, there might be problems with the data format from our server. Please try again in few seconds." delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
                           [alert show];
                           [alert release];
                       }
                   }
                     errorBlock:^(NSError *error){
                         NSDictionary *userInfo = [error userInfo];
                         NSString *errorString = [userInfo objectForKey:@"NSLocalizedDescription"];
                         UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Alert !" message:errorString delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
                         [alert show];
                         [alert release];
                     }
                     httpMethod:@"POST"];
    }
    else {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Alert" message:@"No internet connections, please check your settings." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alertView show];
        [alertView release];
    }
}


#pragma mark - UITextFieldDelegate methods

- (void)textFieldDidBeginEditing:(UITextField *)textField {
    activeField = textField;
}

- (void)textFieldDidEndEditing:(UITextField *)textField {
    
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    //    NSUInteger newLength = [textField.text length] + [string length] - range.length;
    //    if(newLength > 10) {
    //        return NO;
    //    }
    return YES;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    if(activeField == skypeTextField) {
        [emailTextField becomeFirstResponder];
    }
    else {
        [activeField resignFirstResponder];
    }
    
    return YES;
}



@end
